"""
用户账户相关功能【 注册，短信，登录，注销
"""
import uuid

from django.conf import settings
import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Q

# from web.forms.account import RegisterModelform, SendSmsForm, RegisterModelformPost, LoginSmsForm
from web.forms.account import *
from web import models
from io import BytesIO
from utils.image_code import check_code


def register(request):
    """ 注册 """
    if request.method == 'GET':
        form = RegisterModelform()
        return render(request, 'register.html', {'form': form})

    # print(request.POST)
    # form = RegisterModelform(data=request.POST)
    # if form.is_valid():
    #     print(form.cleaned_data)
    #     form.pop('mobile_phone')
    #     # 验证通过，写入数据库(密码要写密文)
    #     form.save()
    #     return JsonResponse({'status': True, 'data': '/login'})
    # print(form.errors)
    # return JsonResponse({'status': False, 'error': form.errors})


def register_post(request):
    """ 提交  [注册"""
    form = RegisterModelformPost(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # form.pop('mobile_phone')
        # 验证通过，写入数据库(密码要写密文)
        # form.save()     # 用户表中创建了一条记录

        # 注册成功后 拿到注册用户对象  【 models.UserInfo.objects.filter(id='新注册的id').first()
        instance = form.save()  # 用户表中创建了一条记录

        # 获取价格策略表的数据
        price_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()

        # 创建一条交易记录
        # 中间件获取价格策略【额度】的方式一
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_object,
            count=0,
            price=0,
            # datetime.datetime.now() 获取当前时间
            start_datetime=datetime.datetime.now(),
            end_datetime=None
        )
        # 方式二就不写

        return JsonResponse({'status': True, 'data': '/login/'})
    # print(form.errors)
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """ 发送短信 """
    # 在forms中
    # print(request.GET)

    # tpl = request.GET.get('tpl')
    # sms_tpl = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    # print(tpl)
    # print(sms_tpl)

    # mobile_phone = request.GET.get('mobile_phone')
    # sms_template_id = settings.TENCENT_SMS_TEMPLATE['tpl']

    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空，格式是否正确
    if form.is_valid():
        # 发短信
        # 写到redis
        # print(form.is_valid())
        # print('*' * 10)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """ 短信登录 """
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})


def login_sms_post(request):
    """ 点击登录 """
    # form = LoginSmsForm(data=request.POST)
    form = LoginSmsFormPost(data=request.POST)
    if form.is_valid():
        user_object = form.cleaned_data['mobile_phone']
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 7)  # 自动修改session过期时间

        # 用户输入手机号验证码
        # user_object = form.cleaned_data['mobile_phone']
        # # 用户信息放入session
        # print(user_object.username)
        # print(user_object.email)

        return JsonResponse({'status': True, 'data': '/index/'})

    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """ 账户密码登录 """
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})

    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # 用户名密码登录
        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()

        # （手机号=mobile_phone and pwd=pwd） or （邮箱=email and pwd=pwd）
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            # 用户密码正确
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 7)  # 自动修改session过期时间

            return redirect('/index/')
        # 用户密码不正确主动在错误列表中增加
        form.add_error('username', '用户名或密码错误')

    return render(request, 'login.html', {'form': form})


def image_code(request):
    """ 生成图片验证码 """
    img_object, code = check_code()
    print(code)

    # 写入到自己的session中 （以便后续获取这个验证码去进行校验
    request.session['image_code'] = code
    # 设置session 60秒之后超时【 过了60s图片验证码无效
    request.session.set_expiry(60)  # 自动修改session过期时间

    # return HttpResponse('图片内容')
    stream = BytesIO()
    img_object.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    """ 退出 """
    # 当前用户的session清除掉【两种都行
    # request.session.clear()
    request.session.flush()
    return redirect('/index/')
